<?php

namespace backend\extensions;

use yii\base\Behavior;
use yii\web\Controller;
use backend\extensions\ApiHttpException;

/**
 * Desc 验证签名类
 * @author HUI
 */
class HttpSignAuth extends Behavior {

    public $key = 'a3fe3c339a43833d1836c12eda977058';
    public $sign = 'sign';
    
    public $optional = [];

    /**
     * Desc 绑定事件和处理器，从而扩展类的功能表现
     * * */
    public function events() {
        return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
    }

    public function beforeAction($event) {
        if(in_array(\Yii::$app->controller->route, $this->optional)){
            return true;
        }
        $headers = \Yii::$app->getRequest()->getHeaders();
        $sign = $headers->get('sign');
        $timestamp = $headers->get('timestamp');
        if(empty($sign) || empty($timestamp)){
            $sign = \Yii::$app->request->get('sign');
            $timestamp = \Yii::$app->request->get('timestamp');
        }
        if (empty($sign) || empty($this->checkSign($sign, $timestamp))) {
            return (new ApiHttpException())->renderException(new \Exception('SIGN-非法请求！！！',201));
        }
        return true;
    }

    private function checkSign($sign, $timestamp) {
        //签名20秒内有效
//        if($time+20 < time()){
//            return false;
//        }
        return md5($this->key . $timestamp) === $sign;
    }
    
    

}
